package cn.lili.controller.wxpay;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.lili.common.utils.SnowFlake;
import cn.lili.common.utils.SpringContextUtil;
import com.alibaba.fastjson.JSON;
import com.jfinal.json.FastJson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Ret;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.CustomServiceApi;
import com.jfinal.weixin.sdk.api.MediaApi;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.weixin.sdk.kit.SignatureCheckKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Map;

/**
 * @author User
 */
@SuppressWarnings("DuplicatedCode")
@Controller
@RequestMapping({"/buyer/wx/msg"})
@Slf4j
public class MsgController extends BaseController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @RequestMapping("")
    public void index(HttpServletRequest request, HttpServletResponse response) throws Exception {

        String token = ApiConfigKit.getApiConfig().getToken();

        boolean isValidSign = SignatureCheckKit.me.checkSignature(StringUtils.defaultIfEmpty(request.getParameter("signature"), ""), token, StringUtils.defaultIfEmpty(request.getParameter("timestamp"), ""), StringUtils.defaultIfEmpty(request.getParameter("nonce"), ""));
        if (isValidSign) {
            String echoStr = request.getParameter("echostr");
            if (StringUtils.isNotEmpty(echoStr)) {
                log.info("微信消息接口认证：{}", echoStr);
                render(response, echoStr);
                return;
            }

            handleMessage(request);
            render(response, "success");
            return;
        } else {
            log.info("微信消息接口签名错误");
        }
        render(response, "error");
    }

    private void handleMessage(HttpServletRequest request) throws Exception {
        String xmlMsg = HttpKit.readData(request);
        if (StringUtils.isNotEmpty(xmlMsg)) {
            Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);
            String msgType = params.get("MsgType");
            String fromUserName = params.get("FromUserName");
            if (StringUtils.equals(msgType, "event")) {
                String event = params.get("Event");
                String eventKey = params.get("EventKey");
                log.info("接收微信事件：{}", JSON.toJSONString(params));
                switch (event) {
                    case "subscribe":
                        handleScan(StringUtils.removeStart(eventKey, "qrscene_"), fromUserName, request);
                        break;
                    case "SCAN":
                        handleScan(eventKey, fromUserName, request);
                        break;
                    case "CLICK":
                        handleClick(eventKey, fromUserName, request);
                        break;
                    default:
                        break;
                }
            } else if (StringUtils.equals(msgType, "text")) {
                handleText(params.get("Content"), fromUserName, request);
            }
        }
    }

    private void handleClick(String event, String openId, HttpServletRequest request) {
        CustomServiceApi.sendText(openId, "点击了：" + event);
        if ("test_native".equals(event)) {
//            ApiConfig ac = ApiConfigKit.getApiConfig();
//            Prop prop = PropKit.use("wx.properties");
//            //下单
//            String appId = ac.getAppId();
//            String partner = prop.get("merchantId");
//
//            String notifyUrl = getBaseUrl(Objects.requireNonNull(WebUtils.getRequest())) + "/wx/native/v3/do_notify";
//            String orderId = "T" + System.currentTimeMillis();
//            String jsonStr;
//            Ret params = Ret.create()
//                    .set("appid", appId)
//                    .set("mchid", partner)
//                    .set("description", "商城订单支付")
//                    .set("out_trade_no", orderId)
//                    .set("notify_url", notifyUrl)
//                    .set("amount", Ret.create("total", RandomUtils.nextInt(10, 100)));
//
//            log.info("微信支付Native请求参数：{}", JSON.toJSONString(params));
//
//            Ret result;
//            try {
//                result = SpringUtils.getBean(WxPayService.class).paymentNative(params);
//            } catch (GeneralSecurityException | IOException | NotFoundException | HttpCodeException e) {
//                log.error("下单失败", e);
//                result = Ret.fail();
//            }
//
//            log.info("微信支付Native请求结果：{}", result.toJson());
//            if (result.isFail()) {
//                log.error("下单失败：{}", result.getStr("code"));
//                CustomServiceApi.sendText(openId, "下单失败：" + result.getStr("code"));
//                return;
//            } else {
//                jsonStr = result.getStr("code_url");
//            }
//
//            CustomServiceApi.sendText(openId, jsonStr);
//            log.info("\r\n回调地址：{}\r\n支付参数：{}", notifyUrl, jsonStr);

        } else {

        }

    }

    private void handleScan(String scene, String openId, HttpServletRequest request) throws Exception {
        if (StringUtils.isEmpty(scene)) {
            CustomServiceApi.sendText(openId, "欢迎关注");
        } else {
            String content = stringRedisTemplate.opsForValue().get("wxpay:" + scene);
            if (StringUtils.isNotEmpty(content)) {
                CustomServiceApi.sendText(openId, "请稍等片刻~~~");
                Ret param = FastJson.getJson().parse(content, Ret.class);

                CreateOrderController createOrderController = (CreateOrderController) SpringContextUtil.getBean("createOrderController");
                String url = createOrderController.doNative(scene, param, request);
                CustomServiceApi.sendImage(openId, "");

                if (StringUtils.isNotBlank(url)) {

                    File qrFile = new File(FileUtils.getTempDirectory(), SnowFlake.getIdStr() + ".jpg");
                    QrCodeUtil.generate(url, 150, 150, qrFile);
                    ApiResult apiResult = MediaApi.uploadMedia(MediaApi.MediaType.IMAGE, qrFile);
                    CustomServiceApi.sendText(openId, "请长按识别");
                    CustomServiceApi.sendImage(openId, apiResult.getStr("media_id"));
                    FileUtils.deleteQuietly(qrFile);
                }
            }
        }
    }

    private void handleText(String content, String openId, HttpServletRequest request) {
        log.info("接收微信消息：{} {}", openId, content);
//        String c = Redis.use().get("wxpay:" + content);
//        if (StringUtils.isEmpty(c)) {
//            //CustomServiceApi.sendText(openId, "请点击链接");
//        } else {
        if ("openid".equals(content)) {
            log.info("发送openid:{}", openId);
            CustomServiceApi.sendText(openId, openId);
        }
//        }
    }
}
